package com.bigfans.catalogservice.api;

import com.bigfans.catalogservice.model.ImageGroup;
import com.bigfans.catalogservice.service.product.ProductImageService;
import com.bigfans.catalogservice.service.product.ProductService;
import com.bigfans.framework.plugins.UploadResult;
import com.bigfans.framework.web.BaseController;
import com.bigfans.framework.web.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lichong
 * @create 2018-03-14 下午7:51
 **/
@RestController
public class ProductImageApi extends BaseController{

    @Autowired
    private ProductImageService productImageService;
    @Autowired
    private ProductService productService;

    @GetMapping(value = "/images")
    public RestResponse listImages(@RequestParam(value = "prodId") String prodId) throws Exception {
        List<ImageGroup> imageGroups = productImageService.listProductImages(prodId);
        return RestResponse.ok(imageGroups);
    }

    @PostMapping(value = "/productImg/upload")
    public RestResponse uploadImg(@RequestParam("file") MultipartFile image) throws Exception{
        UploadResult uploadResult = productService.uploadImage(image.getInputStream(), this.getUploadFileExt(image));
        RestResponse resp = new RestResponse();
        Map<String , Object> data = new HashMap<>();
        data.put("storageType", uploadResult.getStorageType());
        data.put("filePath", uploadResult.getFilePath());
        data.put("fileKey", uploadResult.getFileKey());
        return resp;
    }

    @PostMapping(value = "/productImg/remove")
    public RestResponse removeImg(@RequestBody Map<String , Object> params) throws Exception{
        UploadResult uploadResult = productService.removeImage((String)params.get("file"));
        RestResponse resp = new RestResponse();
        if(!uploadResult.isSuccess()){
            resp.setStatus(404);
            resp.setMessage("删除图片失败");
        }
        return resp;
    }

    protected String getUploadFileExt(MultipartFile file){
        return file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.')+1);
    }

}
